﻿using System.Collections.Concurrent;

namespace Mohe.Scada.WebApi.Cache
{
    public class MyMemoryCache : ICache
    {

        private static readonly Lazy<ICache> lazy = new Lazy<ICache>(
           () =>
           {
               var db = new MyMemoryCache();

               return db;
           });

        public static ICache Cache { get { return lazy.Value; } }

        private static readonly ConcurrentDictionary<string, object> m_pairs = new();

        public void Clear()
        {
            m_pairs.Clear();
        }

        public bool ContainKey(string key)
        {
            if (string.IsNullOrEmpty(key)) return false;
            return m_pairs.ContainsKey(key);
        }

        public object GetCache(string key)
        {
            if (string.IsNullOrEmpty(key))
                return null;
            if (m_pairs.TryGetValue(key, out var value))
            {
                return value;
            }
            return null;
        }




        public void Remove(string key)
        {
            if (string.IsNullOrEmpty(key))
                return;
            m_pairs.TryRemove(key, out var value);
        }

        public void SetCache(string key, object value)
        {
            if (string.IsNullOrEmpty(key)) return;
            if (ContainKey(key))
            {
                Remove(key);
            }

            m_pairs.TryAdd(key, value);
        }
    }
}
